package com.voxel.sense.infomsg.module.map.location;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.location.Location;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.com.common.app.BaseActivity;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;
import com.voxel.sense.infomsg.widget.map.utils.PoiOverlay;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;

/**
 * Created by chenyiyao on 2019/03/1.
 * 检索指定位置的坐标
 */
public class SearchLocationMapActivity extends BaseActivity implements AMap.OnMyLocationChangeListener {

    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    @BindView(R.id.map_view)
    MapView map_view;
    @BindView(R.id.tv_record)
    TextView tv_record;
    @BindView(R.id.btn_search)
    Button btn_search;
    @BindView(R.id.ibtn_location)
    ImageButton ibtn_location;
    @BindView(R.id.et_search)
    AppCompatAutoCompleteTextView et_search;

    //位置标记
    Marker screenMarker = null;
    private LatLng mLocationLatLng;

    public static void show(Activity context) {
        context.startActivityForResult(new Intent(context,
                SearchLocationMapActivity.class),IntentConstants.ARC_SEARCH_COORD);
    }


    public static void show(Activity context, double latitude, double longitude) {
        Intent intent = new Intent(context, SearchLocationMapActivity.class);
        intent.putExtra(IntentConstants.LATITUDE, latitude);
        intent.putExtra(IntentConstants.LONGITUDE, longitude);
        context.startActivityForResult(intent,IntentConstants.ARC_SEARCH_COORD);

    }


    //地图控制类
    private AMap aMap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        map_view.onCreate(savedInstanceState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        map_view.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        map_view.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map_view.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        map_view.onDestroy();
    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_search_location_map;
    }

    @Override
    protected void initData() {
        super.initData();
        if (aMap == null) {
            aMap = map_view.getMap();
            setUpMap();
        }

        Intent intent = getIntent();
        double latitude = intent.getDoubleExtra(IntentConstants.LATITUDE, 0);
        double longitude = intent.getDoubleExtra(IntentConstants.LONGITUDE, 0);
        if (latitude == 0 || longitude == 0) {
            //若无上层activity中传递过来的坐标，则使用定位
            LatLng latLng = new LatLng(Constants.latitude, Constants.longitude, true);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        } else {
            //将地图中心转移到指定位置
            LatLng latLng = new LatLng(latitude, longitude, true);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        }
    }

    @Override
    protected void initEven() {
        super.initEven();
        //地图加载监听
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                addMarkerInScreenCenter();
            }
        });

        titlebar.setRightTextAndLis("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                HandlerETTextChangeEvent(s.toString().trim());
            }
        });


        et_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                searchPoiEvent();
            }
        });

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchPoiEvent();
            }
        });

        ibtn_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLocationLatLng != null) {
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(mLocationLatLng));
                }
            }
        });

    }

    private void HandlerETTextChangeEvent(String newText) {
        if (!TextUtils.isEmpty(newText)) {
            InputtipsQuery inputquery = new InputtipsQuery(newText, "");
            Inputtips inputTips = new Inputtips(SearchLocationMapActivity.this, inputquery);
            inputTips.setInputtipsListener(new Inputtips.InputtipsListener() {
                @Override
                public void onGetInputtips(List<Tip> tipList, int rCode) {
                    handlerSearchTip(tipList, rCode);
                }
            });
            inputTips.requestInputtipsAsyn();
        }
    }

    /**
     * 处理查询结果
     *
     * @param tipList
     * @param rCode
     */
    private void handlerSearchTip(List<Tip> tipList, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {// 正确返回
            List<String> listString = new ArrayList<String>();
            for (int i = 0; i < tipList.size(); i++) {
                listString.add(tipList.get(i).getName());
            }
            ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
                    getApplicationContext(),
                    R.layout.layout_textview_search_tip, listString);
            et_search.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        } else {
            ToastUtil.showToastLong(SearchLocationMapActivity.this, rCode);
        }
    }

    /**
     * 搜索指定地点
     */
    private void searchPoiEvent() {
        String searchKey = et_search.getText().toString();
        if (!TextUtils.isEmpty(searchKey)) {
            showProgressDialog("");
// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
            PoiSearch.Query query = new PoiSearch.Query(searchKey, "", ""
            );
            // 设置每页最多返回多少条poiitem
            query.setPageSize(10);
            //设置获取第一页
            query.setPageNum(1);
            PoiSearch poiSearch = null;
            try {
                poiSearch = new PoiSearch(this, query);
            } catch (AMapException e) {
                e.printStackTrace();
            }
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                @Override
                public void onPoiSearched(PoiResult poiResult, int rCode) {
                    handlerPoiListenerEvent(query, poiResult, rCode);
                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {

                }
            });
            poiSearch.searchPOIAsyn();
        } else {
            ToastUtil.showToastLong(this, "请输入地址");
        }
    }

    /**
     * 处理poi搜索结果
     */
    private void handlerPoiListenerEvent(PoiSearch.Query query, PoiResult poiResult, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getQuery() != null) {// 搜索poi的结果
                if (poiResult.getQuery().equals(query)) {// 是否是同一条
                    poiResult = poiResult;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

                    if (poiItems != null && poiItems.size() > 0) {
                        aMap.clear();// 清理之前的图标
                        screenMarker = null;
                        //添加图钉位置

                        //添加返回的结果集
                        PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
                        poiOverlay.removeFromMap();
                        poiOverlay.addToMap();
                        poiOverlay.zoomToSpan();
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        //没有搜索到数据，但有推荐城市信息
                        ToastUtil.showToastLong(Factory.app(), R.string.no_search_result);
                    } else {
                        ToastUtil.showToastLong(Factory.app(), R.string.no_search_result);
                    }
                }
            } else {
                ToastUtil.showToastLong(Factory.app(), R.string.no_search_result);
            }
        } else {
            ToastUtil.showToastLong(this, rCode);
        }
        dismissProgressDialog();
        addMarkerInScreenCenter();
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        // 如果要设置定位的默认状态，可以在此处进行设置
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        aMap.setMyLocationStyle(myLocationStyle);

        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER));
        //设置SDK 自带定位消息监听
//        aMap.setOnMyLocationChangeListener(this);
        aMap.setOnMyLocationChangeListener(this);
    }


    @Override
    public void onMyLocationChange(Location location) {
        // 定位回调监听
        if (location != null) {
            double latitude = getIntent().getDoubleExtra(IntentConstants.LATITUDE, 0);
            double longitude = getIntent().getDoubleExtra(IntentConstants.LONGITUDE, 0);
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            if (longitude == 0 && latitude == 0 && mLocationLatLng == null) {
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
            }

            mLocationLatLng = latLng;
            Bundle bundle = location.getExtras();
            if (bundle != null) {
                //定位成功

            } else {
            }

        } else {
        }
    }


    /**
     * 在屏幕中心添加一个Marker
     */
    private void addMarkerInScreenCenter() {
        if (screenMarker == null) {
            LatLng latLng = aMap.getCameraPosition().target;
            //添加marker标记,放在地图中间
            Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
            screenMarker = aMap.addMarker(new MarkerOptions()
                    .anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.purple_pin)));
            //设置Marker在屏幕上,不跟随地图移动
            screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(IntentConstants.LATITUDE, aMap.getCameraPosition().target.latitude);
        intent.putExtra(IntentConstants.LONGITUDE, aMap.getCameraPosition().target.longitude);
        setResult(RESULT_OK, intent);
        super.onBackPressed();

    }
}
